package com.clouddms.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Cloud-DMS 系统配置类
 *
 * @author Cloud-DMS Team
 * @version 1.0.0
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "clouddms")
public class CloudDmsConfig implements WebMvcConfigurer {

    /**
     * 存储配置
     */
    private Storage storage = new Storage();

    /**
     * 安全配置
     */
    private Security security = new Security();

    /**
     * 备份配置
     */
    private Backup backup = new Backup();

    /**
     * 清理配置
     */
    private Cleanup cleanup = new Cleanup();

    @Data
    public static class Storage {
        private String basePath = "uploads/";
        private String backupPath = "backups/";
        private long maxFileSize = 52428800; // 50MB
        private String allowedExtensions = "jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,ppt,pptx,txt,zip,rar";
    }

    @Data
    public static class Security {
        private Jwt jwt = new Jwt();
        private Encryption encryption = new Encryption();

        @Data
        public static class Jwt {
            private String secret = "CloudDMS2024SecretKeyForJWT1234567890";
            private long expiration = 86400000; // 24小时
            private String header = "Authorization";
            private String prefix = "Bearer ";
        }

        @Data
        public static class Encryption {
            private String algorithm = "AES";
            private String key = "CloudDMSAESKey2024";
            private String enabledExtensions = "pdf,doc,docx,xls,xlsx";
        }
    }

    @Data
    public static class Backup {
        private boolean enabled = true;

        private int autoBackupInterval = 60;    //1min
        private long maxBackupSize = 5;    //5GB
        private String backupBasePath = "backups/";
        private boolean autoBackupEnabled = true;

        private String schedule = "0 0 2 * * ?"; // 每天凌晨2点
        private int retentionDays = 30;
    }

    @Data
    public static class Cleanup {
        private boolean enabled = true;
        private String schedule = "0 0 3 * * ?"; // 每天凌晨3点
        private int deletedFileRetentionDays = 7;
    }

    /**
     * 初始化配置
     */
    @PostConstruct
    public void init() {
        try {
            // 创建存储目录
            createDirectoryIfNotExists(storage.getBasePath());
            createDirectoryIfNotExists(storage.getBackupPath());

            // 创建用户目录结构
            String usersPath = storage.getBasePath() + "users";
            createDirectoryIfNotExists(usersPath);

            System.out.println("Cloud-DMS 配置初始化完成:");
            System.out.println("  存储路径: " + new File(storage.getBasePath()).getAbsolutePath());
            System.out.println("  备份路径: " + new File(storage.getBackupPath()).getAbsolutePath());
            System.out.println("  最大文件大小: " + (storage.getMaxFileSize() / 1024 / 1024) + "MB");
            System.out.println("  加密算法: " + security.getEncryption().getAlgorithm());

        } catch (Exception e) {
            System.err.println("配置初始化失败: " + e.getMessage());
            throw new RuntimeException("配置初始化失败", e);
        }
    }

    /**
     * 配置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射上传文件路径
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + new File(storage.getBasePath()).getAbsolutePath() + "/");

        // 映射静态资源
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");

        // 映射测试页面
        registry.addResourceHandler("/test/**")
                .addResourceLocations("classpath:/templates/");
    }

    /**
     * 创建目录（如果不存在）
     */
    private void createDirectoryIfNotExists(String path) throws Exception {
        if (!Files.exists(Paths.get(path))) {
            Files.createDirectories(Paths.get(path));
            System.out.println("创建目录: " + new File(path).getAbsolutePath());
        }
    }

    /**
     * 获取用户存储路径
     */
    public String getUserStoragePath(Long userId) {
        return storage.getBasePath() + "users" + File.separator + "user_" + userId;
    }

    /**
     * 获取用户备份路径
     */
    public String getUserBackupPath(Long userId) {
        return storage.getBackupPath() + "user_" + userId;
    }

    /**
     * 检查文件扩展名是否被允许
     */
    public boolean isAllowedExtension(String extension) {
        if (extension == null) return false;
        String[] allowed = storage.getAllowedExtensions().split(",");
        for (String ext : allowed) {
            if (ext.trim().equalsIgnoreCase(extension.trim())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查文件是否需要加密
     */
    public boolean needsEncryption(String extension) {
        if (extension == null) return false;
        String[] encryptExts = security.getEncryption().getEnabledExtensions().split(",");
        for (String ext : encryptExts) {
            if (ext.trim().equalsIgnoreCase(extension.trim())) {
                return true;
            }
        }
        return false;
    }
}